#include "toolmainwindow.h"
#include "ui_toolmainwindow.h"
#include <QtWidgets>
#include "connectorwidget.h"
#include "qdebug.h"
#include "QMessageBox"

ToolMainWindow::ToolMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ToolMainWindow)
{
    //init
    ui->setupUi(this);
    //setWindowState(Qt::WindowMaximized);
    m_port = new QSerialPort();

    m_cnct = new ConnectorWidget(m_port);
    m_viewer = new viewer(m_port);

//    ///<line edit clicked
//    connect(ui->lineEdit_address, SIGNAL(clicked()), this, SLOT(on_lineedit_address_clicked()));
//    connect(ui->lineEdit_id,  SIGNAL(clicked()), this, SLOT(on_lineedit_id_clicked()));

//    //recv print
    connect(m_viewer,SIGNAL(data_print(QByteArray)),this,SLOT(data_print(QByteArray)));

//    ui->horizontalLayout->layout()->setAlignment(Qt::AlignLeft);
}

ToolMainWindow::~ToolMainWindow()
{
    delete ui;
    delete m_port;
    delete m_cnct;
    delete m_viewer;
}

void ToolMainWindow::on_action_connector_triggered()
{
    m_cnct->show();
}


void ToolMainWindow::on_action_viewer_triggered()
{
    m_viewer->show();
}


void ToolMainWindow::data_print(QByteArray data)
{
    qDebug()<<"REcved:"<<data;
    File file = File(data);
    file.AnalyseRawData();
}


void ToolMainWindow::on_actionfile_triggered()
{
}

/**
 * @breif click button to open a directory
 * @para
 * @return
*/
void ToolMainWindow::on_pushButton_clicked()
{
    QString directory =
            QDir::toNativeSeparators(QFileDialog::getExistingDirectory(this, tr("Find Files"), QDir::currentPath()));
    if(directory.size() < 3)
        return;

    QStringList filter;
        filter << "*";

    ///< 目标文件存储目录创建
    QString file_save_dir_str = QString(QDir:: currentPath() + "/Filerecv" );
    QDir file_save_dir_qdir(file_save_dir_str);
        if (!file_save_dir_qdir.exists()) {
            if (file_save_dir_qdir.mkpath(".")) {
                qDebug() << "文件目录创建成功" << file_save_dir_str;
            } else {
                qDebug() << "文件目录创建失败" << file_save_dir_str;
            }
        }

    ///< add file to QString list
    QDirIterator it(directory, filter, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
    qDebug()<<"directory opend...";

    ///< file open
    QFile file(QDir:: currentPath() + "\\zzddata.txt" );
    if (file.open(QIODevice::WriteOnly)) {
        qDebug() << "File created:" << QDir:: currentPath() + "\\zzddata.txt";
    } else {
        qDebug() << "Failed to create file:" << QDir:: currentPath() + "\\zzddata.txt";
    }

    while (it.hasNext())///< 一个文件轮询一次
    {
        ///< 1. load a file
        qDebug()<<"\n load file...";
        SendFile sendfile(it.next());
        ///< 2. open a file
        qDebug()<<"open file...";
        sendfile.FileDataSave();
        ///< 3. send to port
        qDebug()<<"send file...";
        QString file_name = Dir2Name(directory, sendfile.m_file);
        qDebug()<<"work dir:"<<directory<<"\n send file name:"<<file_name;
#if 0
        ///< 文件夹特殊处理
        QFileInfo file_or_dir(directory + file_name);
        if(file_or_dir.isDir())
        {
            qDebug()<<file_or_dir<<"is dir\n";
            m_viewer->send2Port(QString("[tagFiledir]"));
            m_viewer->send2Port(file_name);
            continue;//是文件夹直接返回
        }
        else
        {
            qDebug()<<file_or_dir<<"is file\n";
            m_viewer->send2Port(QString("[tagFilename]"));
        }
        m_viewer->send2Port(file_name);
        m_viewer->send2Port(QString("[tagFilesize]"));
        m_viewer->send2Port(QString::number(sendfile.m_size));
        m_viewer->send2Port(QString("[tagFiledata]\n"));//数据之前一定要换行
        m_viewer->send2Port(sendfile.m_data);
        //qDebug()<<"发送:\n"<<sendfile.m_data.size()<<sendfile.m_data;
#endif
        ///< 文件夹特殊处理
        QFileInfo file_or_dir(directory + file_name);
        if(file_or_dir.isDir())
        {
            qDebug()<<file_or_dir<<"is dir\n";
            file.write(QByteArray("[tagFiledir]"));
            file.write(file_name.toUtf8());
            continue;//是文件夹直接返回
        }
        else
        {
            file.write(QByteArray("[tagFilename]"));
        }

        file.write(file_name.toUtf8());
        file.write(QByteArray("[tagFilesize]"));
        file.write(QByteArray::number(sendfile.m_size));
        file.write(QByteArray("[tagFiledata]\n"));//数据之前一定要换行
        file.write(sendfile.m_data);
    }
    file.close();
}

// 创建文件夹（如果不存在）
void createDirectory(const QString& dirPath) {
    ///< 组地址
    QStringList dirs = dirPath.split("/", QString::SkipEmptyParts);
    QString current_dir = QString(QDir:: currentPath() + "/Filerecv" );
    for(int i = 0; i < dirs.size(); i++)
    {
        current_dir += ( "/" + dirs.at(i));
    }

    QDir dir(current_dir);
    if (!dir.exists()) {
        if (dir.mkpath(".")) {
            qDebug() << "Directory created:" << dirPath;
        } else {
            qDebug() << "Failed to create directory:" << dirPath;
        }
    }
}

// 创建文件并写入数据
void createFile(const QString& filename, const QByteArray& data) {

    ///< 组地址
    QStringList dirs = filename.split("/", QString::SkipEmptyParts);
    QString dir = QString(QDir:: currentPath() + "/Filerecv" );
    for(int i = 0; i < dirs.size(); i++)
    {
        dir += ( "/" + dirs.at(i));
    }

    QFile file(dir);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(data);
        file.close();
        qDebug() << "File created:" << dir;
    } else {
        qDebug() << "Failed to create file:" << dir;
    }
}
// 定义根目录宏
#define ROOT_DIR "C:\\Users\\admin\\Desktop\\build-tool-Desktop_Qt_5_12_4_MinGW_32_bit-Debug\\Filerecv" // 替换为你的目标根目录
void parseAndCreate(const QString& filePath) {
    QFile file(filePath);
       if (!file.open(QIODevice::ReadOnly)) {
           qDebug() << "Failed to open file:" << filePath;
           return;
       }

       QByteArray fileContent = file.readAll(); // 读取整个文件内容
       file.close();

       qint64 pos = 0;
       QString currentDir; // 当前文件夹路径
       while (pos < fileContent.size()) {
           // 查找 [tagFiledir]
           qint64 dirStart = fileContent.indexOf("[tagFiledir", pos);
           if (dirStart != -1) {
               qint64 dirEnd = fileContent.indexOf("[tagFile", dirStart + 1);
               if (dirEnd == -1) break;

               // 提取文件夹路径
               currentDir = fileContent.mid(dirStart + 12, dirEnd - (dirStart + 12)).trimmed();
               currentDir.replace("\\", "/"); // 统一路径分隔符

               // 创建文件夹
               createDirectory(currentDir);

               // 更新位置
               pos = dirEnd;
           }
           else {
               break;
           }
       }

       pos = 0;
       file.close();
       while (pos < fileContent.size()) {
           // 查找 [tagFiledir]
//           qint64 dirStart = fileContent.indexOf("[tagFiledir", pos);
//           if (dirStart != -1) {
//               qint64 dirEnd = fileContent.indexOf("[tagFile", dirStart + 1);
//               if (dirEnd == -1) break;

//               // 提取文件夹路径
//               currentDir = fileContent.mid(dirStart + 12, dirEnd - (dirStart + 12)).trimmed();
//               currentDir.replace("\\", "/"); // 统一路径分隔符

//               // 创建文件夹
//               createDirectory(currentDir);

//               // 更新位置
//               pos = dirEnd;
//           }

           // 查找 [tagFilename]
           qint64 filenameStart = fileContent.indexOf("[tagFilename]", pos);
           if (filenameStart == -1) break;

           // 查找 [tagFilesize]
           qint64 filesizeStart = fileContent.indexOf("[tagFilesize]", filenameStart);
           if (filesizeStart == -1) break;

           // 查找 [tagFiledata]
           qint64 filedataStart = fileContent.indexOf("[tagFiledata]", filesizeStart);
           if (filedataStart == -1) break;

           // 提取文件名
           QString filename = fileContent.mid(filenameStart + 13, filesizeStart - (filenameStart + 13)).trimmed();
           filename.replace("\\", "/");

           // 拼接完整文件路径
           QString fullFilePath = filename;//= currentDir.isEmpty() ? filename : currentDir + "/" + filename;

           // 提取文件大小
           QString filesizeStr = fileContent.mid(filesizeStart + 13, filedataStart - (filesizeStart + 13)).trimmed();
           qint64 filesize = filesizeStr.toLongLong();

           // 提取文件数据
           qint64 filedataEnd = filedataStart + 13 + filesize;
           if (filedataEnd > fileContent.size()) {
               qDebug() << "Invalid file size for:" << fullFilePath;
               break;
           }
           QByteArray filedata = fileContent.mid(filedataStart + 14, filesize);

           // 创建文件
           createFile(fullFilePath, filedata);

           // 更新位置
           pos = filedataEnd;
       }
}

void ToolMainWindow::on_pushButton_analyse_file_clicked()
{
    QString path = QFileDialog::getOpenFileName(this,"打开","../");
    if(path.isEmpty() == false)
    {
        /// 1.判断文件能否打开
        QFile file(path);
        //qDebug()<<"file name:"<<path<<"open file ok?"<<file.open(QIODevice::ReadOnly);
        //qDebug()<<file.readLine();

        /// 2.
        //File file2 = File(QString("init class File"));
        // 解析数据并创建文件夹和文件
        parseAndCreate(path);

    }
}
